package reflect;

import java.lang.reflect.Field;

import org.junit.Test;

public class Demo4 {
	/**
	 * 反射类的字段
	 * @author xiayaqiong
	 * @throws Exception 
	 *
	 */
@Test
public void test() throws Exception{
	Person person=new Person();
	Class class1= Class.forName("reflect.Person");
    Field field=	class1.getField("name");
	field.set(person, "xiayq");
	System.out.println(person.getName());
}

@Test
public void test2() throws Exception{
	Person person=new Person();
	person.setName("xiyaq");
	Class class1= Class.forName("reflect.Person");
    Field field=	class1.getField("name");
    String result= (String) field.get(person);
    System.out.println(result);
}
//反射final字段
@Test
public void test3() throws Exception{
	Person person=new Person();
	person.setName("xiyaq");
	Class class1= Class.forName("reflect.Person");
    Field field=	class1.getField("password");
   // field.set(person, "qwe");//不可行 finnal字段不可改
    System.out.println(field.get(person));
}

//反射私有字段
@Test
public void test4() throws Exception{
	Person person=new Person();
	person.setName("xiyaq");
	Class class1= Class.forName("reflect.Person");
  Field field=	class1.getDeclaredField("age");
   field.setAccessible(true);
   field.set(person, 456);
   System.out.println(field.get(person));
}
}
